/**
 * @(#) com.kfx.e_news.utils 2015/10/22;
 *
 *
 * Copyright (c), 2009 深圳孔方兄金融信息服务有限公司（Shenzhen kfxiong
 * Financial Information Service Co. Ltd.）
 *
 *
 * 著作权人保留一切权利，任何使用需经授权。
 */
package com.zztl.infiniteBand.util

import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageManager
import android.telephony.TelephonyManager


object AppInfoUtils {

    private var isCheck = false
    /**
     * 获取应用程序版本名称
     *
     * @return
     */

    //can't reach
    val appVersionName: String
        get() {
            try {
                val pm = UiUtils.context.packageManager
                val packinfo = pm.getPackageInfo(UiUtils.context.packageName, 0)
                return packinfo.versionName
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                return ""
            }

        }

    /**
     * 获取应用程序版本号
     *
     * @return
     */
    //can't reach
    val appVersionCode: Int
        get() {
            try {
                val pm = UiUtils.context.packageManager
                val packinfo = pm.getPackageInfo(UiUtils.context.packageName, 0)
                return packinfo.versionCode
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                return 0
            }

        }

    /**
     * 获取设备Id
     *
     * @return
     */
    val deviceId: String
        get() {
            val manager = UiUtils.context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            return manager.simSerialNumber
        }


    val packageName: String
        get() = UiUtils.context.getPackageName()

    /**
     * 检测是否开启了某个权限
     *
     * @param permissionName
     * @return
     */
    fun checkPermission(permissionName: String): Boolean {

        return UiUtils.context.checkCallingOrSelfPermission(permissionName) == PackageManager.PERMISSION_GRANTED
    }

    fun checkPermissions(permissionNames: Array<String>): Boolean {
        for (i in permissionNames.indices) {
            val permissionName = permissionNames[i]
            isCheck = UiUtils.context.checkCallingOrSelfPermission(permissionName) == PackageManager.PERMISSION_GRANTED
            if (!isCheck) {
                return false
            }
        }
        return true

    }


    /**
     * app是否在运行
     *
     * @param context
     * @return
     */
    fun isAppRunning(context: Context): Boolean {
        val packageName = context.packageName
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = am.getRunningTasks(100)
        for (info in list) {
            if (info.topActivity.packageName == packageName && info.baseActivity.packageName == packageName) {
                return true
            }
        }
        return false
    }
}
